<?php

namespace iterator;
// 定义节点类，表示流程中的一个节点
class ProcessNode
{
    private string $name;
    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function toString(): string
    {
        return "ProcessNode: " . $this->name;
    }
}

// 定义迭代器接口：提供统一的遍历方法
interface Iterator
{
    public function hasNext(): bool;
    public function next(): ProcessNode;
}

// 创建流程迭代器类， 实现迭代器接口
class workFlowIterator implements Iterator
{
    private array $processNodes;
    private int $index;
    public function __construct(array $processNodes)
    {
        $this->processNodes = $processNodes;
        $this->index = 0;
    }
    public function hasNext(): bool
    {
        return $this->index < count($this->processNodes);
    }
    public function next(): ProcessNode
    {
        if (!$this->hasNext()) {
            throw new \Exception("没有更多的节点");
        }
        return $this->processNodes[$this->index++];
    }
}

// 定义具体的流程类， 实现节点数组并返回迭代器
class workFlow
{
    /** @var ProcessNode[] */
    private array $processNodes = [];
    // 添加节点到流程中
    public function addNode(ProcessNode $processNode): void
    {
        $this->processNodes[] = $processNode;
    }
    // 创建流程迭代器
    public function createIterator(): workFlowIterator {
        return new workFlowIterator($this->processNodes);
    }
}



// 测试
// 创建流程对象，并添加节点
$workflow = new workFlow();
$workflow->addNode(new ProcessNode("开始"));
$workflow->addNode(new ProcessNode("审批"));
$workflow->addNode(new ProcessNode("处理"));
$workflow->addNode(new ProcessNode("通知"));
$workflow->addNode(new ProcessNode("结束"));
$it = $workflow->createIterator();
$hasNext = $it->hasNext();
echo "流程是否有节点：" . ($hasNext ? "有" : "无") . "\n";
while ($it->hasNext()) {
    try {
        $node = $it->next();
        echo $node->toString() . "\n";
    } catch (\Exception $e) {
        echo $e->getMessage() . "\n";
    }
}